package com.gears_software.sxdc.dccx.ui.fragment;


import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.adapter.CheZhuXingChengListAdapter;
import com.gears_software.sxdc.dccx.data.finder.ICPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.IVehicleFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.CPOrderModel;
import com.gears_software.sxdc.dccx.data.model.MemberModel;
import com.gears_software.sxdc.dccx.data.model.PagedResultModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.VehicleModel;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.activity.AddCarInfoActivity_;
import com.gears_software.sxdc.dccx.ui.activity.LoginActivity_;
import com.gears_software.sxdc.dccx.ui.activity.ReleaseScheduleActivity_;
import com.gears_software.sxdc.dccx.ui.event.LogoutDriverMemberEvent;
import com.gears_software.sxdc.dccx.ui.event.UpdateDriverMemberAndOrderEvent;
import com.gears_software.sxdc.dccx.ui.event.UpdateDriverTripEvent;
import com.gears_software.sxdc.dccx.ui.event.UpdateDriverVehicleFullEvent;
import com.gears_software.sxdc.dccx.ui.event.UpdateTripListEvent;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.github.mzule.activityrouter.router.Routers;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.squareup.otto.Subscribe;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.rest.spring.annotations.RestService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chezhenzhen on 2017/6/27.
 * 车主
 */
@EFragment(R.layout.fragment_carowner)
public class CarOwnerFragment extends Fragment {
    @App
    DCCXApplication app;
    @ViewById
    Button btn_release;
    @ViewById
    XRecyclerView list_xingcheng;
    @ViewById
    TextView txt_username;
    @ViewById
    TextView txt_refresh;
    @ViewById
    TextView txt_nodata_icon;
    @ViewById
    RelativeLayout re_refresh;
    @RestService
    ICPOrderFinder icpOrderFinder;
    @RestService
    IMemberFinder memberFinder;
    @RestService
    IVehicleFinder vehicleFinder;
    @Bean
    GearsErrorHandler errorHandler;
    @Bean
    OttoBus bus;
    @Pref
    DCCXSp_ sp;
    List<CPOrderModel> orderModelList;
    CheZhuXingChengListAdapter adapter;
    int currentPage = 1;
    public String sort = "-departtime";
    MaterialDialogProgress progress;
    MemberModel memberModel;

    @AfterViews
    void created() {
        icpOrderFinder.setRestErrorHandler(errorHandler);
        memberFinder.setRestErrorHandler(errorHandler);
        vehicleFinder.setRestErrorHandler(errorHandler);
        txt_nodata_icon.setTypeface(app.iconfont);
        orderModelList = new ArrayList<CPOrderModel>();
        initXRecyclerView();
        bus.register(this);
        progress = new MaterialDialogProgress(getActivity());
        if (!sp.token().get().equals("")) {
            progress.show("正在加载...");
            getCurrentMember();
            getDriverOrderList();
        }

    }

    void initXRecyclerView() {
        list_xingcheng.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        list_xingcheng.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        list_xingcheng.setLayoutManager(layoutManager);

        list_xingcheng.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        list_xingcheng.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);

        list_xingcheng.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                progress.show("正在加载...");
                getDriverOrderList();
                list_xingcheng.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                getMoreDriverList();
                list_xingcheng.loadMoreComplete();

            }
        });
    }

    @Background
    void getCurrentMember() {
        ResultModel<MemberModel> res = memberFinder.getMember();
        showMemberResult(res);
    }

    @UiThread
    void showMemberResult(ResultModel<MemberModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    memberModel = res.getData();
                    if (memberModel.getFname() != null && !memberModel.getFname().equals("")) {
                        txt_username.setText(memberModel.getFname() + ",你好");
                    } else if (memberModel.getNickname() != null && !memberModel.getNickname().equals("")) {
                        txt_username.setText(memberModel.getNickname() + ",你好");
                    } else {
                        txt_username.setText(memberModel.getDriverphone() + ",你好");
                    }
                }
            }
        }

    }

    @Background
    void getDriverOrderList() {
        currentPage = 1;
        PagedResultModel<CPOrderModel> res = icpOrderFinder.getDriverOrderList(currentPage, sort);
        showResult(res);
    }

    @UiThread
    void showResult(PagedResultModel<CPOrderModel> res) {
        if (res != null) {
            if (res.getErrno() == 0) {
                orderModelList = res.getData().getData();
                adapter = new CheZhuXingChengListAdapter(this, getActivity(), orderModelList);
                list_xingcheng.setAdapter(adapter);
                if (orderModelList == null || orderModelList.size() == 0) {
                    list_xingcheng.setVisibility(View.GONE);
                    re_refresh.setVisibility(View.VISIBLE);
                } else {
                    list_xingcheng.setVisibility(View.VISIBLE);
                    re_refresh.setVisibility(View.GONE);
                }
                adapter.setOnItemClickListener(new CheZhuXingChengListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Routers.open(getActivity(), "gears_dccx://tripinfo/" + orderModelList.get(position).getId());
                    }
                });
            }
        }
        progress.dismiss();
    }

    @Background
    void getMoreDriverList() {
        currentPage++;
        PagedResultModel<CPOrderModel> res = icpOrderFinder.getDriverOrderList(currentPage, sort);
        showMoreResult(res);
    }


    @UiThread
    void showMoreResult(PagedResultModel<CPOrderModel> res) {
        if (res != null) {
            if (res.getErrno() == 0) {
                List<CPOrderModel> moreList = new ArrayList<CPOrderModel>();
                moreList = res.getData().getData();
                if (moreList != null && moreList.size() > 0) {
                    for (int i = 0; i < moreList.size(); i++) {
                        orderModelList.add(moreList.get(i));
                    }
                }
                adapter = new CheZhuXingChengListAdapter(this, getActivity(), orderModelList);
                adapter.notifyDataSetChanged();
//                list_xingcheng.setAdapter(adapter);
                adapter.setOnItemClickListener(new CheZhuXingChengListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Logger.d(position);
                        Routers.open(getActivity(), "gears_dccx://tripinfo/" + orderModelList.get(position).getId());
                    }
                });
                list_xingcheng.setNoMore(true);
            }
        }
    }

    //设为车满事件总线注册
    @Subscribe
    public void onUpdateDriverVehicleFull(UpdateDriverVehicleFullEvent event) {
        int position = event.getPosition();
        setVehicelFull(position);
    }

    @Background
    void setVehicelFull(int position) {
        ResultModel<String> res = icpOrderFinder.setVehicleFull(orderModelList.get(position).getId());
        showVehicleFullResult(res);
    }

    @UiThread
    void showVehicleFullResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(getActivity(), "设为车满成功", app.SHORT, app.SUCCESS);
                list_xingcheng.refresh();
            } else {
                TastyToast.makeText(getActivity(), "设为车满失败", app.SHORT, app.ERROR);
            }
        }
    }

    //用户登录成功后获取当前用户和列表 事件总线注册
    @Subscribe
    public void onUpdateMemberAndOrder(UpdateDriverMemberAndOrderEvent event) {
        progress.show("正在加载...");
        getCurrentMember();
        getDriverOrderList();
    }

    //用户退出登录 事件总线注册
    @Subscribe
    public void onLogouDriverMember(LogoutDriverMemberEvent event) {
        txt_username.setText("大昌用户,您好");
        orderModelList.clear();
        adapter.notifyDataSetChanged();
    }

    @Subscribe
    public void onUpdateTrip(UpdateTripListEvent event) {
        String orderId = event.getOrderid();
        int seat = event.getSeat();
        for (int i = 0; i < orderModelList.size(); i++) {
            if (orderId.equals(orderModelList.get(i).getId())) {
                orderModelList.get(i).setPassengernum(orderModelList.get(i).getPassengernum() - seat);
            }
        }
        adapterChanged();
    }

    @Subscribe
    public void onUpdateDriverTrip(UpdateDriverTripEvent event) {
        int position = event.getPosition();
        CPOrderModel cp = event.getCpOrderModel();
        orderModelList.get(position).setPassengernum(cp.getPassengernum());
        orderModelList.get(position).setDeparttime(cp.getDeparttime());
        orderModelList.get(position).setStartpoint(cp.getStartpoint());
        orderModelList.get(position).setEndpoint(cp.getEndpoint());
        orderModelList.get(position).setCarmodel(cp.getCarmodel());
        orderModelList.get(position).setVehiclecolor(cp.getVehiclecolor());
        orderModelList.get(position).setVehicleno(cp.getVehicleno());
        orderModelList.get(position).setVehicleid(cp.getVehicleid());
        orderModelList.get(position).setPrice(cp.getPrice());
        orderModelList.get(position).setTraveldirection(cp.getTraveldirection());
        adapterChanged();
    }

    /**
     * lileltp 处理刷新失效问题.
     */
    @UiThread
    void adapterChanged() {
        adapter.notifyDataSetChanged();
    }

    @Click
    void btn_release() {
        if (!sp.token().get().equals("")) {
            progress.show("正在加载...");
            getCarSize();
        } else {
            Intent intent = new Intent(getActivity(), LoginActivity_.class);
            startActivityForResult(intent, 1);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            list_xingcheng.refresh();
        } else if (requestCode == 1) {
            if (!sp.token().get().equals("")) {
                getCurrentMember();
            }
        }
    }

    @Background
    void getCarSize() {
        ResultModel<List<VehicleModel>> res = vehicleFinder.getVehicleList();
        showVehicleResutl(res);
    }

    @UiThread
    void showVehicleResutl(ResultModel<List<VehicleModel>> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    List<VehicleModel> listVehicle = res.getData();
                    if (listVehicle != null && listVehicle.size() > 0) {
                        app.addDriverTag();
                        if (memberModel.getCarpooldriveroutlineauditstate() != null && memberModel.getCarpooldriveroutlineauditstate().equals("4")){
                            Intent intent = new Intent(getActivity(), ReleaseScheduleActivity_.class);
                            intent.putExtra("title", "发布行程");
                            intent.putExtra("flag", "add");
                            startActivityForResult(intent, 2);
                        }else{
                            if (orderModelList.size() < 5){
                                Intent intent = new Intent(getActivity(), ReleaseScheduleActivity_.class);
                                intent.putExtra("title", "发布行程");
                                intent.putExtra("flag", "add");
                                startActivityForResult(intent, 2);
                            }else{
                                new MaterialDialog.Builder(getActivity())
                                        .title("提示")
                                        .titleGravity(GravityEnum.CENTER)
                                        .titleColorRes(R.color.colorFontGray)
                                        .content("请联系客服进行线下认证，未进行线下认证，最多可以发布5条行程。")
                                        .contentColorRes(R.color.colorFontGray)
                                        .positiveText("确定")
                                        .buttonsGravity(GravityEnum.CENTER)
                                        .show();
                            }
                        }

//                        Routers.open(getActivity(), "gears_dccx://releasetrip/" + "发布行程" + "/" + "add");
                    } else {
                        new MaterialDialog.Builder(getActivity())
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content("添加车辆信息，即可发布行程。")
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(getActivity(), R.color.colorFontBlue))
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        Intent intent = new Intent(getActivity(), AddCarInfoActivity_.class);
                                        intent.putExtra("title", "添加车辆");
                                        intent.putExtra("flag", "add");
                                        startActivity(intent);

                                    }
                                })
                                .negativeText("取消")
                                .negativeColor(ContextCompat.getColor(getActivity(), R.color.colorFontGray))
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                    }
                                })
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    }
                }
            }

        }
        progress.dismiss();
    }

    @Click
    void txt_refresh() {
        if (!sp.token().get().equals("")) {
            list_xingcheng.refresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bus.unregister(this);
    }
}
